package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mappers.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entyti.User;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     *注册
     */
    @PostMapping("reg")
    public int userReg(@RequestBody UserRegDTO userRegDTO){
        System.out.println("userRegDTO = " + userRegDTO);
        /*
            1.接收参数[已完成]
            2.数据合法性校验[暂时不做，后续用验证框架做]
            3.校验用户名是否被占用[SELECT接口]
                3.1 被占用，return 2;
                3.2 未被占用，[INSERT接口]，return 1;
         */
        UserVO userVO = userMapper.selectUserReg(userRegDTO.getUsername());
        if(userVO!=null){
            return 2;
        }
        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
    }
    /**
     * 登录
     */
    @PostMapping("login")
    public int userLogin(@RequestBody UserLoginDTO userLoginDTO){
        UserVO userVO = userMapper.selectUserReg(userLoginDTO.getUsername());
        if (userVO==null){
            return 3;
        }
        if (userVO.getPassword().equals(userLoginDTO.getPassword())){
            return 1;
        }
        return 2;
    }

    /**
     *获取当前用户
     */
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO =(UserVO) session.getAttribute("user");
        return userVO;
    }

    /**
     *退出登录
     */
    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
